﻿using MediatR;
using S.PurchaseAndSales.Domain.Dto;
using S.PurchaseAndSales.Domain.Model;
using S.PurchaseAndSales.Infrastructure.Interface.PurchaseForm;
using S.PurchaseAndSales.Read.Api.Application.Command.PurchaseFormCommand;
using S.PurchaseAndSales.Read.Api.Dto;

namespace S.PurchaseAndSales.Read.Api.Application.CommandHandlers.PurchaseFormHandler
{
    /// <summary>
    /// 供应商查询分页显示
    /// </summary>
    public class VendorGetPagerCommandHandler : IRequestHandler<VendorGetPagerCommand, Pager<GetVendorPageDto>>
    {
        private readonly IVendorRepository repository;

        public VendorGetPagerCommandHandler(IVendorRepository repository)
        {
            this.repository = repository;
        }
        public async Task<Pager<GetVendorPageDto>> Handle(VendorGetPagerCommand request, CancellationToken cancellationToken)
        { 
            List<GetVendorPageDto> list= (await repository.GetVendorPage()).Where(x => (request.VenDorCode == 0 || x.VenDorCode == request.VenDorCode) && (string.IsNullOrEmpty(request.VenDorName) || x.VendorName.Contains(request.VenDorName)) && (string.IsNullOrEmpty(request.ResponsiblePhone) || x.ResponsiblePhone.Contains(request.ResponsiblePhone)) && (string.IsNullOrEmpty(request.Markets) || x.Markets.Contains(request.Markets)) && (string.IsNullOrEmpty(request.Salesman) || x.Salesman.Contains(request.Salesman)) && (request.UseState == null || x.UseState == request.UseState)).ToList();

            int total = list.Count;
            int page = (int)Math.Ceiling(total * 1.0 / request.PageSize);
            list=list.Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
            return new Pager<GetVendorPageDto>
            {
                TotalCount = total,
                PageCount = page,
                ResultData = list.ToList(),
            };
        }
    }
}
